package com.keyinong.wifiprint;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.bluetooth.BluetoothPrintFormatUtil;
import com.keyinong.qudan.R;
import com.keyinong.qudan.dapter.CaidanAdapter;
import com.keyinong.qudan.entity.GoodsInfoBean;
import com.keyinong.qudan.tools.HttpTools;
import com.keyinong.qudan.tools.Utility;
import com.loopj.android.http.JsonHttpResponseHandler;

public class WifiPrintActivity extends Activity {
	View iscatview = null;
	private CaidanAdapter caidanAdapter;
	private TextView textValue;
	/**菜单列表*/
	private ListView lv;
	private String token;
	static int shuliang=0;
	private static Double zongjia=0.0;
	private TextView tv_shuliang;
	private TextView tv_zongjia;
	private TextView tv_content;
	private TextView tv_fee;
	private String orderno;
	private String order_time;
	private String receive_time;
	private String fee;
	private String recmode;
	private double heji;
	private String note;
	private String guige;
	private ImageButton iv_back;
	private String total;
	private String address;
	private String num1;
	private String num2;
	private String num3;
	private String num4;
	private String ipaddress;
	private String name;
	private String phone;
	private String shoushuofangshi="";
	private String dayno;
	private String aname;
	private String pname;
	private String off;
	private String more;
	private String youhuiquan;
	private String invoice;
	private String mcode=null;
	HttpTools httpTools=null;
	ArrayList<GoodsInfoBean> detaillist = new ArrayList<GoodsInfoBean>();

	LinkedHashMap<String, LinkedList<String>> menuMsgMap = new LinkedHashMap<String, LinkedList<String>>();

	LinkedList<String> gonds=new LinkedList<String>();
	BluetoothPrintFormatUtil printFormatUtil = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_main);
		SharedPreferences spuser=getSharedPreferences("spuser", Context.MODE_PRIVATE);
		if(!"".equals(spuser))
		{
			num1=spuser.getString("num1", "");
			num2=spuser.getString("num2", "");
			num3=spuser.getString("num3", "");
			num4=spuser.getString("num4", "");
		}
		ipaddress=num1+"."+num2+"."+num3+"."+num4;
		Button btnPrint = (Button) findViewById(R.id.btnPrint);
		textValue = (TextView) findViewById(R.id.text_valueback);
		address = getIntent().getStringExtra("address");
		zongjia=0.0;
		shuliang=0;
		orderDetail();
		lv=(ListView)findViewById(R.id.lv_caipin);
		tv_shuliang=(TextView)findViewById(R.id.tv_shuliang);
		tv_zongjia=(TextView)findViewById(R.id.tv_zongjia);
		tv_content=(TextView)findViewById(R.id.tv_content);
		tv_fee=(TextView)findViewById(R.id.tv_fee);
		iv_back=(ImageButton)findViewById(R.id.iv_back);
		iv_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});


		btnPrint.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				printorder();
			}
		});
		

	}
	
	private void printorder() {
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("token", "");
		String orderid = getIntent().getStringExtra("id");
//		TTs();
		if (httpTools == null) {
			httpTools = new HttpTools(WifiPrintActivity.this);
		}
		httpTools.printorder(token, orderid, new JsonPrintOrder());
	}
	
	private class JsonPrintOrder extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			
			try {
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if (code == true) {
//					JSONObject object = response.getJSONObject("data");
					Toast.makeText(WifiPrintActivity.this, msg, Toast.LENGTH_SHORT).show();
					dayin();
//					Log.i("lh", "printtype---"+"0");
				} else {
					dayindialog();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	

	private void dayin() {
//		Log.i("info", ipaddress);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Pos pos1 = new Pos(ipaddress, 4000,"GBK");
					final String value = pos1.getPosStatus();
					WifiPrintActivity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							textValue.setText(value);
						}
					});
					String[] split = value.split(",");
					if (value.equals("16,0,0,0,")){//每个状态码代表含义以后补充
//						printorder();
						Pos pos = new Pos(ipaddress, 9100,"GBK");
						//初始化打印机
						pos.initPos();
						pos.bold(true);
						pos.printTabSpace(2);
						pos.printWordSpace(1);
						pos.selectCommand(pos.DOUBLE_HEIGHT_WIDTH);
						pos.printText("17度E"+"\n");
//						pos.printText(""+aname+"\n");
						
						pos.printLocation(1);
						pos.printText(""+aname+"\n");
						pos.printText(""+shoushuofangshi+" \n");
						pos.printText("厨房第" + dayno+"单"+" \n");
//						pos.selectCommand(pos.DOUBLE_HEIGHT_WIDTH);
//						pos.printTabSpace(2);
//						pos.printWordSpace(1);		
						pos.printLocation(0);
						pos.selectCommand(pos.NORMAL);
						pos.printTextNewLine("--------------------------------");
						pos.bold(false);
						pos.selectCommand(pos.NORMAL);
						pos.printText("名称            " + "数量     "+"单价");
						pos.selectCommand(pos.DOUBLE_HEIGHT_WIDTH);
						menuMsgMap.put("", gonds);
						
						pos.printText(printFormatUtil.printMenuMSG(menuMsgMap));
						pos.selectCommand(pos.NORMAL);
						//            pos.printTextNewLine("----------------------------------------------");
						pos.printText("数量：" + shuliang+"份"+"   ");
						pos.printText("  配送费：" + fee +"元"+ " \n");
						pos.printText("总价：" + heji +"元"+pname+youhuiquan+ " \n");
						pos.printText("备注：" + note+ " \n");
						//			sendMessage("日期：" +date+ "\n");
						pos.printText("订单编号："+orderno+" \n");
						pos.printText("下单时间："+order_time+" \n");
						pos.printText("取餐时间："+receive_time+" \n");
						pos.printText("姓名："+name+" \n");
						pos.printText("联系电话："+phone+" \n");			
						pos.printText("配送地址："+address+" \n");
						pos.printText("发票抬头："+(TextUtils.isEmpty(invoice)?"无":invoice)+" \n");
//						pos.printText("信用编码："+(TextUtils.isEmpty(mcode)?"无":mcode)+" \n");
						
						pos.printTextNewLine("--------------------------------");
						pos.printText(printFormatUtil.printTitle("请妥善保管好购物凭证"+"\n"));
						pos.printText(printFormatUtil.printTitle("谢谢惠顾！")+ "\n");
//						Log.i("zq", "address---"+address);
						
						pos.printLine(6);
//						pos.feedAndCut();
						pos.closeIOAndSocket();
						pos = null;
					}
				} catch (Exception e) {

					e.printStackTrace();
				}
			}


		}).start();

		

	}

	private void orderDetail() {
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("token", "");
//		Log.i("zq", "token--"+token);
		String orderid = getIntent().getStringExtra("id");
		//			TTs();
		if (httpTools == null) {
			httpTools = new HttpTools(WifiPrintActivity.this);
		}
		httpTools.detail(token, orderid, new JsonOrderDetail());
	}

	private class JsonOrderDetail extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			try {
				boolean code = response.getBoolean("code");
				if (code == true) {
					JSONObject object = response.getJSONObject("data");
					JSONArray array = object.getJSONArray("details");
					dayno = object.getString("dayno");
					orderno = object.getString("orderno");
					order_time = object.getString("order_time");
					receive_time = object.getString("receive_time");
					fee = object.getString("fee");
					note = object.getString("note");
					recmode = object.getString("recmode");
					total = object.getString("total");
					name = object.getString("name");
					phone = object.getString("phone");
					aname = object.getString("aname");
					pname = object.getString("pname");
					off = object.getString("off");
					more = object.getString("more");
					invoice=object.getString("invoice");
//					mcode=object.getString("code");
//					if(mcode.equals("null")){
//						mcode="";
//					}
					
					for (int i = 0; i < array.length(); i++) {
						JSONObject object2 = array.getJSONObject(i);
						String id = object2.getString("id");
						String name = object2.getString("name");
						String amount = object2.getString("amount");
						String price = object2.getString("price");
						String content = object2.getString("content");
						String sname = object2.getString("sname");
						shuliang +=Integer.parseInt(amount);
						zongjia= zongjia+Integer.parseInt(amount)*Double.parseDouble(price);
						heji = Double.parseDouble(total)+Integer.parseInt(fee);
						double jiage = Integer.parseInt(amount)*Double.parseDouble(price);
						detaillist.add(new GoodsInfoBean(name, amount, price, content,sname));
						if (sname.equals("null")||sname.equals("")) {
							guige="";
						}else {
							guige="("+sname+")";
						}
						gonds.add(" \n"+name+guige);
						gonds.add("*"+amount);
						gonds.add(""+jiage);
						//							gonds.add(content+" - ");
					}
					if (off.equals("null")) {
						youhuiquan="";
					}else {
						youhuiquan="(满"+more+"减"+off+")";
					}
					if (pname.equals("null")) {
						pname="";
					}else {
						pname="("+pname+")";
					}
					if(note.equals("")||note.equals("null")){
						tv_content.setText("无");
						note="无";
					}else{
						tv_content.setText(note);
					}
					if(recmode.equals("1")){
						tv_fee.setVisibility(View.INVISIBLE);
						shoushuofangshi="店内自提";
					}else if (recmode.equals("2")) {
						tv_fee.setVisibility(View.VISIBLE);
						tv_fee.setText("(含运费￥"+fee+")");
						shoushuofangshi="送货上门";
					}else if (recmode.equals("3")) {
						tv_fee.setVisibility(View.INVISIBLE);
						shoushuofangshi="堂吃";
					}
					if(fee.equals("0")){
						address="无";
					}
					tv_shuliang.setText(""+shuliang+"份");
					tv_zongjia.setText(""+heji+"元");

					caidanAdapter = new CaidanAdapter(getApplicationContext(), detaillist);
					lv.setAdapter(caidanAdapter);
					lv.setDivider(null);
					Utility.setListViewHeightBasedOnChildren(lv);
					//							Log.i("zq", "list"+array.length());
				} else {
					String msg = response.getString("msg");
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				String responseBody, Throwable e) {
			super.onFailure(statusCode, headers, responseBody, e);
		}
		
		

	}

	/**是否重复打印弹窗*/
	private void dayindialog() {

		final Dialog dialog = new Dialog(WifiPrintActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		iscatview = LayoutInflater.from(WifiPrintActivity.this).inflate(
				R.layout.dialog_phone, null);
		TextView tv_no = (TextView) iscatview.findViewById(R.id.tv_no2);
		TextView tv_yes = (TextView) iscatview.findViewById(R.id.tv_yes2);
		dialog.setContentView(iscatview);
		dialog.show();
		tv_no.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		tv_yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dayin();
				dialog.dismiss();
			}
		});
	}

}
